package cn.doitedu.hbase.hbasemr;

import com.google.gson.Gson;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableReducer;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;

import java.io.IOException;

public class MovieRateSum {

    public static class M extends Mapper<LongWritable, Text,Text, IntWritable>{

        Gson gson = new Gson();

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            try {
                String json = value.toString();

                String[] split = json.split("\"");

                context.write(new Text(split[3]), new IntWritable(Integer.parseInt(split[7])));
            }catch (Exception e){

            }

        }
    }


    public static class R extends TableReducer<Text,IntWritable, ImmutableBytesWritable>{

        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {

            int sum = 0;
            for (IntWritable value : values) {
                sum += value.get();
            }

            Put put = new Put(key.toString().getBytes());
            put.addColumn("f".getBytes(),"rate".getBytes(), Bytes.toBytes(sum));

            context.write(null,put);
        }
    }



    public static void main(String[] args) throws Exception {


        Configuration conf = new Configuration();
        conf.set("hbase.zookeeper.quorum","spark01:2181,spark02:2181");

        Job job = Job.getInstance(conf);


        job.setMapperClass(M.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);


        job.setInputFormatClass(TextInputFormat.class);
        //job.setOutputFormatClass(TableOutputFormat.class);

        TableMapReduceUtil.initTableReducerJob("wordcount",R.class,job);

        FileInputFormat.setInputPaths(job,new Path("E:\\mrdata\\json\\input\\rating.json"));

        boolean res = job.waitForCompletion(true);


    }



}
